package com.icoolkj.ms.auth.service;

import com.icoolkj.ms.api.auth.dto.CaptchaDTO;
import com.icoolkj.ms.common.core.exception.IcoolkjMSException;
import com.icoolkj.ms.common.core.response.ServerResponseEntity;
import com.icoolkj.ms.common.core.utils.SpringContextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author icoolkj
 * @version 1.0
 * @description 授权策略
 * @createDate 2025/02/23 22:16
 */
public interface IAuthStrategy {

    String BASE_AUTH_STRATEGY = "AuthStrategyImpl";
    Logger logger = LoggerFactory.getLogger(IAuthStrategy.class);

    /**
     * 根据授权类型验证验证码
     * @param grantType 授权类型
     * @param captchaDTO 验证码信息
     * @return 验证结果
     */
    static boolean validateCodeByGrantType(String grantType, CaptchaDTO captchaDTO) {
        String authStrategyName = grantType + BASE_AUTH_STRATEGY;
        if (!SpringContextUtils.containsBean(authStrategyName)) {
            logger.error("授权类型 {} 对应的策略 Bean {} 不存在", grantType, authStrategyName);
            throw new IcoolkjMSException("授权类型不正确!");
        }
        IAuthStrategy instance = (IAuthStrategy) SpringContextUtils.getBean(authStrategyName);
        return instance.validateCode(captchaDTO);
    }

    /**
     * 验证验证码
     * @param captchaDTO 验证码信息
     * @return 验证结果
     */
    boolean validateCode(CaptchaDTO captchaDTO);

    /**
     * 获取验证码生成策略
     * @param grantType 授权类型
     * @return 验证码生成策略实例
     */
    static ServerResponseEntity getGenerateCaptcha(String grantType,  String captchaKey) {
        String authStrategyName = grantType + BASE_AUTH_STRATEGY;
        if (!SpringContextUtils.containsBean(authStrategyName)) {
            logger.error("授权类型 {} 对应的验证码生成策略 Bean {} 不存在", grantType, authStrategyName);
            throw new IcoolkjMSException("未找到对应的验证码生成策略!");
        }
        IAuthStrategy instance = (IAuthStrategy) SpringContextUtils.getBean(authStrategyName);
        return instance.generateCaptcha(captchaKey);
    }

    /**
     * 生成验证码
     * @param captchaKey 生成验证码KEY
     * @return 验证结果
     */
    ServerResponseEntity generateCaptcha(String captchaKey);

}

